# coding=utf-8

'''
requires Python 3.6 or later
pip install requests
'''
import base64
import json
import uuid
import requests
from config import BYTEDANCE_SPEECH_CONFIG
import io


# 填写平台申请的 appid, access_token 以及 cluster
appid = BYTEDANCE_SPEECH_CONFIG['APPID']
access_token = BYTEDANCE_SPEECH_CONFIG['ACCESS_TOKEN']
cluster = BYTEDANCE_SPEECH_CONFIG['CLUSTER']

voice_type = BYTEDANCE_SPEECH_CONFIG['VOICE_TYPE']


def get_tts(text, retry_count=3):
    host = "openspeech.bytedance.com"
    api_url = f"https://{host}/api/v1/tts"

    header = {"Authorization": f"Bearer;{access_token}"}

    request_json = {
        "app": {
            "appid": appid,
            "token": "access_token",
            "cluster": cluster
        },
        "user": {
            "uid": "388808087185088"
        },
        "audio": {
            "voice_type": voice_type,
            "encoding": "wav",
            "rate": 16000,
            "speed_ratio": 0,
            "volume_ratio": 1,
            "pitch_ratio": 1,
        },
        "request": {
            "reqid": str(uuid.uuid4()),
            "text": text,
            "text_type": "plain",
            "operation": "query",
            "with_frontend": 1,
            "frontend_type": "unitTson"

        }
    }
    for _ in range(retry_count):
        try:
            resp = requests.post(api_url, json.dumps(request_json), headers=header)
            if resp.status_code == 200:
                if "data" in resp.json():
                    data = resp.json()["data"]
                    return base64.b64decode(data)
                else:
                    print(f"No data in response for text: {text}")
                    return None
            else:
                print(f"Error response for text: {text}. Status code: {resp.status_code}")
                return None
        except Exception as e:
            print(f"Error occurred for text: {text}. Exception: {e}")
    return None


# 分片合成音频
def combine_texts_to_audio(text):
    chunks = [text[i:i + 100] for i in range(0, len(text), 100)]
    combined_audio = bytearray()
    for index, chunk in enumerate(chunks):
        chunk_audio = get_tts(chunk)
        if chunk_audio:
            combined_audio += chunk_audio
            # print(f"Successfully added chunk {index} to audio. Chunk text: {chunk}")
        else:
            print(f"Failed to get audio for chunk: {chunk}")
            # 记录合成失败的分片
            with open("./audio/failed_chunks.log", "a") as f:
                f.write(f"Failed chunk: {chunk}\n")
    if combined_audio:
        with open("./audio/temp_output.wav", "wb") as f:
            f.write(combined_audio)
        print(f"Successfully saved combined audio.")
    else:
        print("No audio data to save.")
        # 记录没有音频数据可保存的情况
        with open("./audio/no_audio_data.log", "a") as f:
            f.write(f"No audio data for text: {text}\n")

if __name__ == '__main__':
    long_text = """从前有一只小老虎，它非常喜欢在森林里玩耍。有一天，它遇到了一只小兔子，小兔子非常可爱，小老虎立刻被它吸引住了。

小老虎决定和小兔子一起玩耍，它们一起跳过了小溪，穿过了森林，玩得非常开心。但是，当夜幕降临，小兔子必须回家时，小老虎感到非常失落。

从那以后，小老虎每天都会去寻找小兔子，和它一起玩耍。它们一起度过了许多美好的时光，小老虎也变得越来越开心。

但是，有一天，小兔子告诉小老虎，它必须离开森林，去一个新的地方生活。小老虎非常伤心，它不知道该怎么办。

最后，小老虎决定去寻找小兔子，告诉它自己的感受。它穿过了森林，越过了山脉，终于找到了小兔子。

小老虎对小兔子说：“我非常喜欢你，我不想你离开我。”小兔子感动地抱住了小老虎，说：“我也喜欢你，但是我必须去新的地方生活。”

。"""
    combine_texts_to_audio(long_text)